package com.my.content.near;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.my.content.bean.NearBean;
import com.my.content.contants.Contants;
import com.my.content.utlis.OkHttpClientHelper;
import com.my.content.liveproject.R;
import com.my.content.utlis.PullToRefreshLableUtils;
import com.my.content.utlis.UIManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
    这里是附近页面
 */
public class NearFragment extends Fragment {


    @BindView(R.id.near_seeAll)
    TextView nearSeeAll;
    @BindView(R.id.near_gridView)
    GridView nearGridView;
    @BindView(R.id.near_pullToRefreshScrollView)
    PullToRefreshScrollView nearPullToRefreshScrollView;

    private static GridViewAdapter adapter;
    static Handler mHandler = new Handler() {

        private List<NearBean.FlowBean> data;
        private List<NearBean.FlowBean> subData;

        @Override
        //处理消息
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //判断标志位
            switch (msg.arg1) {
                case 1:
                    //接收解析数据集合
                    data = (List<NearBean.FlowBean>) msg.obj;
                    subData = new ArrayList<>();
                    for (int i = 0; i < 18; i++) {
                        subData.add(data.get(i));
                    }
                    break;
                case 3:
                    for (int i = 0; i < 18; i++) {
                        subData.add(subData.size(), data.get(subData.size() + i));
                    }
                    break;
                case 4:
                    if (data.get(0).equals(subData.get(0))) {
//                        Toast.makeText(getActivity(),"暂时没有比这更棒的才艺表演了",Toast.LENGTH_SHORT).show();
                    } else {
                        subData.add(0, data.get(0));
                    }
            }
            adapter.setData(subData);
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_near, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter = new GridViewAdapter(getActivity());

        nearGridView.setAdapter(adapter);

        //获取数据
        loadJson();

        //刷新
        refresh();
    }

    //上下拉刷新
    private void refresh() {
        //设置刷新的模式
        nearPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        //设置刷新的样式
        PullToRefreshLableUtils.setPullToRefreshScrollLable(nearPullToRefreshScrollView);
        //设置上下拉刷新的监听
        nearPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //设置最近刷新时间
                PullToRefreshLableUtils.showScrollRefreshTime(refreshView, getActivity());
                //下拉刷新
                pullDownToRefresh();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //设置最近刷新时间
                PullToRefreshLableUtils.showScrollRefreshTime(refreshView, getActivity());
                //上拉加载
                pullUpToRefresh();

            }
        });
    }

    //上拉加载数据
    private void pullUpToRefresh() {
        refreshResult(3);
    }

    //下拉刷新
    private void pullDownToRefresh() {
        refreshResult(4);
    }

    private void refreshResult(final int caseIndex) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //创建消息对象
                        Message message = mHandler.obtainMessage();
                        //设置标志位
                        message.arg1 = caseIndex;
                        //使用handler发送信息
                        mHandler.sendMessage(message);
                        nearPullToRefreshScrollView.onRefreshComplete();
                    }
                });
            }
        }).start();
    }

    private void loadJson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //okhttp解析url
                    String stringFromURL = OkHttpClientHelper.getStringFromURL(getActivity(), Contants.Nearby, null);
                    //gson解析数据
                    Gson gson = new Gson();
                    NearBean nearBean = gson.fromJson(stringFromURL, NearBean.class);
                    //得到解析所需的集合
                    final List<NearBean.FlowBean> flowBeen = nearBean.getFlow();

                    //运行在主线程
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //创建消息对象
                            Message message = mHandler.obtainMessage();
                            //设置标志位
                            message.arg1 = 1;
                            //设置包含内容
                            message.obj = flowBeen;
                            //使用handler发送信息
                            mHandler.sendMessage(message);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @OnClick(R.id.near_seeAll)
    public void onClick() {
        Intent intent = new Intent(getActivity(),NearSeeAllActivity.class);
        startActivityForResult(intent,1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}
